package com.yuerlive.rainbow.widget;

import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.OvershootInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.yuerlive.rainbow.R;
import com.yuerlive.rainbow.entity.Gift;
import com.yuerlive.rainbow.utils.GlideUtil;

import java.text.BreakIterator;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * Created by xiaoyi on 2017/5/24.
 */

public class GiftShowLayout extends LinearLayout {
    private List<View> giftViewCollection = new ArrayList<View>();
    private LinkedBlockingQueue<Gift> queue;//礼物的队列

    private final static int SHOW_GIFT_FLAG = 1;//显示礼物
    private final static int GET_QUEUE_GIFT = 0;//从队列中获取礼物
    private final static int REMOVE_GIFT_VIEW = 2;//当礼物的View显示超时，删除礼物View

    private Map<String, Gift> mapCaches = new LinkedHashMap<>();
    private Timer timer;
    private Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case SHOW_GIFT_FLAG:
                    Gift showVo = (Gift) msg.obj;
                    showGift(showVo);
                    break;
                case GET_QUEUE_GIFT:
                    Gift vo = queue.poll();
                    if (vo != null) {//如果从队列中获取的礼物不为空，那么就将礼物展示在界面上
                        Message giftMsg = new Message();
                        giftMsg.obj = vo;
                        giftMsg.what = SHOW_GIFT_FLAG;
                        handler.sendMessage(giftMsg);
                    } else {
                        handler.sendEmptyMessageDelayed(GET_QUEUE_GIFT, 1000);//如果这次从队列中获取的消息是礼物是空的，则一秒之后重新获取
                    }
                    break;
                case REMOVE_GIFT_VIEW:
                    final int index = (int) msg.obj;
                    Log.e("TAG", "index  " + index);
                    if (getChildCount() > index) {
                        removeGiftView(index);
                    }
                    break;
            }
        }
    };
    private TimerTask giftLooper = new TimerTask() {
        @Override
        public void run() {
            if (!mapCaches.isEmpty()) {
                Gift popGift = null;
                int max = 0;
                for (Map.Entry<String, Gift> entry : mapCaches.entrySet()) {
                    Gift g = entry.getValue();
                    if (g.getNum() > max) {
                        max = g.getNum();
                        popGift = g;
                    }
                }
                if (popGift != null) {
                    mapCaches.remove(popGift.getUserId() + popGift.getName());
                    queue.add(popGift);
                }
            }
        }

    };

    private TimerTask giftShowTask = new TimerTask() {
        @Override
        public void run() {
            int count = getChildCount();
            int giftNum = 0;
            if (getChildCount() > 0) {
                giftNum = (int) getChildAt(0).findViewById(R.id.tvCount).getTag();
            }
            int index = 0;
            for (int i = 0; i < count; i++) {
                View view = getChildAt(i);
                int num = (int) view.findViewById(R.id.tvCount).getTag();
                if (giftNum > num) {
                    giftNum = num;
                    index = i;
                }

            }
            if (getChildCount() > 0) {
                CircleImageView header = (CircleImageView) getChildAt(index).findViewById(R.id.imgHeader);
                long nowtime = System.currentTimeMillis();
                long upTime = (long) header.getTag();
                if ((nowtime - upTime) >= 5000) {
                    Message msg = new Message();
                    msg.obj = index;
                    msg.what = REMOVE_GIFT_VIEW;
                    handler.sendMessage(msg);
                }
            }
        }
    };

    public GiftShowLayout(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        inAnim = (TranslateAnimation) AnimationUtils.loadAnimation(getContext(), R.anim.gift_in);
        outAnim = (TranslateAnimation) AnimationUtils.loadAnimation(getContext(), R.anim.gift_out);
        giftNumAnim = new NumAnim();
        queue = new LinkedBlockingQueue<Gift>();
        timer = new Timer();
        timer.schedule(giftLooper, 500, 500);
        timer.schedule(giftShowTask, 2000, 2000);

    }

    /**
     * 动画相关
     */
    private NumAnim giftNumAnim;
    private TranslateAnimation inAnim;
    private TranslateAnimation outAnim;


    /**
     * 添加礼物view,(考虑垃圾回收)
     */
    private View addGiftView(Gift gift) {
        View view = null;
        if (giftViewCollection.size() <= 0) {
            /*如果垃圾回收中没有view,则生成一个*/
            view = LayoutInflater.from(getContext()).inflate(R.layout.item_gift, null);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            CircleImageView header = (CircleImageView) view.findViewById(R.id.imgHeader);
            ImageView giftIcon = (ImageView) view.findViewById(R.id.imgGift);

            GlideUtil.load(getContext(), gift.getSenderIcon(), header);
            GlideUtil.load(getContext(), gift.getNoFrameIcon(), giftIcon);
            TextView tvNick = (TextView) view.findViewById(R.id.tvNickName);
            TextView tvGift = (TextView) view.findViewById(R.id.tvGift);
            tvNick.setText(gift.getFromNick());
            tvGift.setText("送出了一个" + gift.getName());

            lp.topMargin = 10;
            view.setLayoutParams(lp);
            addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() {
                @Override
                public void onViewAttachedToWindow(View view) {
                }

                @Override
                public void onViewDetachedFromWindow(View view) {
                    giftViewCollection.add(view);
                }
            });
        } else {
            view = giftViewCollection.get(0);
            giftViewCollection.remove(view);
        }
        return view;
    }

    /**
     * 删除礼物view
     */
    private void removeGiftView(final int index) {
        final View removeView = getChildAt(index);
        outAnim.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                removeViewAt(index);
                handler.sendEmptyMessage(GET_QUEUE_GIFT);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        });
        removeView.startAnimation(outAnim);
    }

    /**
     * 显示礼物的方法
     */
    public void showGift(Gift gift) {
        String tag = gift.getUserId() + gift.getName();
        View giftView = findViewWithTag(tag);
        if (giftView == null) {/*该用户不在礼物显示列表*/

            if (getChildCount() >= 2) {/*如果正在显示的礼物的个数超过两个，那么就移除最后一次更新时间比较长的*/
                View giftView1 = getChildAt(0);
                CircleImageView picTv1 = (CircleImageView) giftView1.findViewById(R.id.imgHeader);
                long lastTime1 = (Long) picTv1.getTag();
                View giftView2 = getChildAt(1);
                CircleImageView picTv2 = (CircleImageView) giftView2.findViewById(R.id.imgHeader);
                long lastTime2 = (Long) picTv2.getTag();
                if (lastTime1 > lastTime2) {/*如果第二个View显示的时间比较长*/
                    removeGiftView(1);
                } else {/*如果第一个View显示的时间长*/
                    removeGiftView(0);
                }
            }

            giftView = addGiftView(gift);/*获取礼物的View的布局*/
            giftView.setTag(tag);/*设置view标识*/

            CircleImageView circleImageView = (CircleImageView) giftView.findViewById(R.id.imgHeader);
            circleImageView.setTag(System.currentTimeMillis());
            final GiftTextView tvCount = (GiftTextView) giftView.findViewById(R.id.tvCount);/*找到数量控件*/
            tvCount.setTag(gift.getNum());
            tvCount.setText("x"+gift.getNum());/*设置礼物数量*/

            addView(giftView);/*将礼物的View添加到礼物的ViewGroup中*/
            invalidate();/*刷新该view*/
            giftView.startAnimation(inAnim);/*开始执行显示礼物的动画*/
            inAnim.setAnimationListener(new Animation.AnimationListener() {/*显示动画的监听*/
                @Override
                public void onAnimationStart(Animation animation) {
                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    giftNumAnim.start(tvCount);
                }

                @Override
                public void onAnimationRepeat(Animation animation) {
                }
            });
        } else {/*该用户在礼物显示列表*/
            CircleImageView CircleImageView = (CircleImageView) giftView.findViewById(R.id.imgHeader);/*找到头像控件*/
            GiftTextView tvCount = (GiftTextView) giftView.findViewById(R.id.tvCount);/*找到数量控件*/
            int showNum = gift.getNum();
            tvCount.setText("x" + showNum);
            tvCount.setTag(showNum);
            CircleImageView.setTag(System.currentTimeMillis());
            giftNumAnim.start(tvCount);
        }
        handler.sendEmptyMessageDelayed(GET_QUEUE_GIFT, 300);
    }

    /**
     * 数字放大动画
     */
    public class NumAnim {
        private Animator lastAnimator = null;

        public void start(View view) {
            if (lastAnimator != null) {
                lastAnimator.removeAllListeners();
                lastAnimator.end();
                lastAnimator.cancel();
            }
            ObjectAnimator anim1 = ObjectAnimator.ofFloat(view, "scaleX", 1.3f, 1.0f);
            ObjectAnimator anim2 = ObjectAnimator.ofFloat(view, "scaleY", 1.3f, 1.0f);
            AnimatorSet animSet = new AnimatorSet();
            lastAnimator = animSet;
            animSet.setDuration(200);
            animSet.setInterpolator(new OvershootInterpolator());
            animSet.playTogether(anim1, anim2);
            animSet.start();
        }
    }

    //放入礼物到队列
    public void addGift(Gift vo) {
        //return queue.add(vo);
        mapCaches.put(vo.getUserId() + vo.getName(), vo);

    }


    public void release() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (giftLooper != null) {
            giftLooper.cancel();
            giftLooper = null;
        }
        if (giftShowTask != null) {
            giftShowTask.cancel();
            giftShowTask = null;
        }

        if (handler!=null){
            handler.removeCallbacksAndMessages(null);
            handler = null;
        }
        removeAllViews();
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        release();
    }

    //开始显示礼物
    public void showGift() {
        handler.sendEmptyMessageDelayed(GET_QUEUE_GIFT, 1000);//轮询队列获取礼物
    }
}
